import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import PublicActivities from '../views/PublicActivities.vue'
import ActivityDetail from '../views/ActivityDetail.vue'
import ActivityManagement from '../views/ActivityManagement.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities',
    name: 'PublicActivities',
    component: PublicActivities,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities/:id',
    name: 'ActivityDetail',
    component: ActivityDetail,
    meta: { requiresAuth: true },
    props: true
  },
  {
    path: '/activity-management',
    name: 'ActivityManagement',
    component: ActivityManagement,
    meta: { 
      requiresAuth: true, 
      requiresAdmin: true 
    }
  },
  {
    path: '*',
    redirect: '/'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin)
  const isAuthenticated = localStorage.getItem('userRole') !== null
  const isAdmin = localStorage.getItem('userRole') === 'admin'

  if (!requiresAuth) {
    return next()
  }

  if (!isAuthenticated) {
    return next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  }

  if (requiresAdmin && !isAdmin) {
    alert('您没有权限访问此页面')
    return next('/')
  }

  next()
})

export default router
